<?php

/**
 * Data Mapper pour la table t_user
 *
 * @package App_Model_Map
 * @author  nroche <nicolas.roche42@gmail.com>
 *
 */
class App_Model_Map_User
{
    /**
     * Table
     *
     * @var Zend_Db_Table_Abstract
     */
    protected $_dbTable;

    /**
     * Crée et retourne une instance de l'objet {@link Zend_Db_Select} pour récupérer les information de la table
     * fsite.
     *
     * @return Zend_Db_Select
     */
    protected function _getFetchAllSelectQuery()
    {
        $columns = array(
                'idUser',
                'profile',
                'publicName',
                'email',
                'password',
                'salt',
                'firstName',
                'lastName',
                "DATE_FORMAT(inscription, '%Y-%m-%d') as inscription",
                'params',
        );

        $database = Zend_Db_Table::getDefaultAdapter();

        return $database->select()->from('t_user', $columns);
        //->order('LOWER(TRIM(sinom_tc)) ' . Zend_Db_Select::SQL_ASC);
    }

    /**
     * Reseigne les attributs d'une instance de App_Model_Vo_User
     *
     * @param mixed             $row    un enregistrement en base. Peut être de
     *                                  type array ou Zend_Db_Table_Row_Abstract
     * @param App_Model_Vo_User $userVO utilisateur
     */
    public function populate($row, App_Model_Vo_User $userVO)
    {
        if ($row instanceof Zend_Db_Table_Row_Abstract) {
            $row = $row->toArray();
        }

        if (isset($row['idUser']))
            $userVO->idUser = $row['idUser'];
        if (isset($row['email']))
            $userVO->email = $row['email'];
        if (isset($row['publicName']))
            $userVO->publicName = $row['publicName'];
        if (isset($row['profile']))
            $userVO->profile = $row['profile'];
        if (isset($row['firstName']))
            $userVO->firstName = $row['firstName'];
        if (isset($row['lastName']))
            $userVO->lastName = $row['lastName'];
        if (isset($row['inscription']))
            $userVO->inscription = $row['inscription'];
        if (isset($row['params'])) {
            if ($row['params'] == null)
                $userVO->params = array();
            else
                $userVO->params = json_decode($row['params']);
        }
    }

    /**
     * Requête tous les utilisateurs en base.
     *
     * @return array tableau d'objets {@link App_Model_User}
     */
    public function fetchAll()
    {
        $database = Zend_Db_Table::getDefaultAdapter();

        $resultSet = $database->query($this->_getFetchAllSelectQuery());

        $entries = array();
        foreach ($resultSet as $row) {
            $userVO = new App_Model_Vo_User();
            $this->populate($row, $userVO);
            $entries[] = $userVO;
        }
        return $entries;
    }

    /**
     * Renvoie l'utilisateur cherché.
     *
     * @param string $email email
     * @param string $pass  pass
     *
     * @return App_Model_Vo_User user
     */
    public function findUser($email, $pass, $key)
    {
        $database = Zend_Db_Table::getDefaultAdapter();

        $select = $this->_getFetchAllSelectQuery()
        ->where('email = ?', $email);

        $rows = $database->fetchAll($select);
        
        if(!$rows || count($rows) != 1)
            return null;

        $row = $rows[0];

        if ($row["password"] != sha1($key . $row["salt"] . $pass))
            return null;

        return $row;
    }

    public function userExists_byIdAndPass($userID, $pass, $key)
    {
        $database = Zend_Db_Table::getDefaultAdapter();

        $select = $this->_getFetchAllSelectQuery()
        ->where('idUser = ?', $userID);

        $rows = $database->fetchAll($select);
        if (!$rows || count($rows) != 1)
            return false;

        $row = $rows[0];

        if ($row["password"] != sha1($key . $row["salt"] . $pass))
            return false;

        return true;
    }

    /**
     * Renvoie l'utilisateur cherché.
     *
     * @param string $params paramatres
     *     contient des array('dbName' => '', 'value' => '')
     *
     * @return App_Model_Vo_User user
     */
    public function findUsersByParams($params)
    {
        $database = Zend_Db_Table::getDefaultAdapter();

        $select = $this->_getFetchAllSelectQuery();

        foreach ($params as $param) {
            $select = $select->where($param['dbName'] . ' = ?', $param['value']);
        }

        $rows = $database->fetchAll($select);
        $results = array();

        foreach ($rows as $row) {
            $userVO = new App_Model_Vo_User();
            $this->populate($row, $userVO);
            $results[] = $userVO;
        }

        return $results;
    }

    /**
     * Ajoute l'utilisateur.
     *
     * @param string $publicName pseudo (nom public)
     * @param string $email adresse e-mail
     * @param string $password mot de passe
     */
    public function addUser($publicName, $email, $password/*, $firstName, $lastName*/)
    {
        $database = Zend_Db_Table::getDefaultAdapter();

        $data = array(
                'publicName' => $publicName,
                'email' => $email,
                'password' => '4b4bdc49912cff177ec14bb0f04756981ae7533b',
                'profile' => 4,
                'salt' => 'salt',
                //                 'firstName' => $firstName,
                //                 'lastName' => $lastName,
                'inscription' => '2011-11-11 20:20:20',
        );

        $database->insert('t_user', $data);
    }

    /**
     * Modifie l'utilisateur.
     *
     * @param int     $idUser paramatres
     * @param array   $data tableau des données à changer sous la forme:
     *     $data = array(
     *         'field1' => 'value1',
     *         'field2' => 'value2',
     *     );
     */
    public function updateUser($idUser, $data)
    {
        $database = Zend_Db_Table::getDefaultAdapter();

        $where = array(
                'idUser = ?' => $idUser,
        );

        $database->update('t_user', $data, $where);
    }

    /**
     * Retourne la liste des film de l'utilisateur
     *
     * @param int $idUser ID utilisateur
     *
     * @return Zend_Db_Select
     */
    public function getFriendsByUserID($idUser)
    {
        $database = Zend_Db_Table::getDefaultAdapter();

        $columns = array(
                'rt_user_friend.idFriend',
                'publicName',
        );

        $query = $database->select()
        ->from('t_user', $columns)
        //         ->join('rt_user_friend', 'rt_user_friend.idUser = ' . $idUser);
        ->join('rt_user_friend', 'rt_user_friend.idUser = t_user.idUser OR rt_user_friend.idFriend = t_user.idUser')
        ->where("(rt_user_friend.idUser = $idUser OR rt_user_friend.idFriend = $idUser) AND t_user.idUser != $idUser")
        ->order('t_user.publicName ' . Zend_Db_Select::SQL_ASC);

        $resultSet = $database->query($query);


        $entries = array();
        foreach ($resultSet as $row) {
            $userVO = new App_Model_Vo_User();
            //             $this->populate($row, $userVO);
            $userVO->idUser = $row['idFriend'];
            $userVO->publicName = $row['publicName'];
            $entries[] = $userVO;
        }
        return $entries;
    }

    /**
     * Retourne la liste des film de l'utilisateur
     *
     * @param int $idUser ID utilisateur
     *
     * @return Zend_Db_Select
     */
    public function getRequestsByUserID($idUser)
    {
        $database = Zend_Db_Table::getDefaultAdapter();

        $columns = array(
                'idMovie',
                'name',
                'urlPicture',
                'rating',
        );

        $query = $database->select()
        ->from('t_user')
        ->join('rt_user_request', 'rt_user_request.idUser = ' . $idUser);

        $resultSet = $database->query($query);

        $entries = array();
        foreach ($resultSet as $row) {
            $movieVO = new App_Model_Vo_Movie();
            $this->populate($row, $movieVO);
            $entries[] = $movieVO;
        }
        return $entries;
    }

    /**
     * Ajoute une demande d'ami
     *
     * @param string $idUser   id de l'utilisateur qui fait la demande
     * @param string $idFriend id de l'utilisateur demandé
     */
    public function addRequest($idUser, $idFriend)
    {
        $database = Zend_Db_Table::getDefaultAdapter();

        $data = array(
                'idUser' => $idUser,
                'idFriend' => $idFriend,
        );

        $database->insert('rt_user_request', $data);
    }

    public function userExists_byPublicName($publicName)
    {
        $database = Zend_Db_Table::getDefaultAdapter();

        $select = $this->_getFetchAllSelectQuery()
        ->where('publicName = ?', $publicName);

        $rows = $database->fetchAll($select);
        if ($rows && count($rows) == 1)
            return true;
        return false;
    }

} // end class